// pages/login/login.ts
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import { getUserInfo } from "../../utils/api";
import { trimStr } from "../../utils/util";

Page({
  data: {
    isAgreement: false,
    passWord: "",
    userName: "",
    pwdErrorMessage: "",
    usnErrorMessage: ""
  },
  // 请求后台
  requestApi() {
    getUserInfo({
      userName: this.data.userName,
      passWord: this.data.passWord
    }).then(res => {
      console.log(res);
      if (res.flag) {
        wx.setStorage({ key: "userInfo", data: res.data });
        wx.switchTab({
          url: "../home/home"
        })
      }
    })
  },
  // 登录
  onLoginFn(e: any) {
    if (!this.data.userName) {
      return;
    }
    if (!this.data.passWord) {
      return;
    }
    if (!this.data.isAgreement) {
      Dialog.alert({
        title: '注意',
        message: '您还未同意我们的的条款内容，请点击确认',
        theme: 'round-button',
      }).then(() => {
        this.requestApi();
      });
      return;
    }
    this.requestApi();
  },
  // 校验用户名的正确性
  synchronousSetUserNameData(msg: any) {
    msg.detail = trimStr(msg.detail);
    const exs = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
    if (!msg.detail) {
      this.setData({
        usnErrorMessage: "账号不允许为空",
        userName: ""
      })
    }
    if (!exs.test(msg.detail)) {
      this.setData({
        usnErrorMessage: "账号不符合邮箱规则请检查",
        userName: ""
      })
    } else {
      this.setData({
        usnErrorMessage: "",
        userName: msg.detail
      })
    }
  },
  // 校验密码正确性
  synchronousSetPassWordData(msg: any) {
    var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
    if (!msg.detail) {
      this.setData({
        passWord: "",
        pwdErrorMessage: "密码不允许为空"
      })
    }
    if (!reg.test(msg.detail)) {
      this.setData({
        passWord: "",
        pwdErrorMessage: "密码为6-16位字母和数字组合 "
      })
    } else {
      this.setData({
        pwdErrorMessage: "",
        passWord: msg.detail
      })
    }
  },
  onAgreementFn(e: any) {
    if (e.detail == "true") {
      this.setData({
        isAgreement: true
      })
    }
  }
})